interface dataFormat{
    name: string
    message?: string  
    cb?: any 
    required?: boolean 
}
/** el-form 配置 :rules=FormRuleUtils.getRules() 获取配置
 *  FormRuleUtils.setChecks([{dataFormat}]) 配置检验
 *  FormRuleUtils.setCheck({dataFormat}) 单个配置校验
 *  FormRuleUtils.check() 校验所有已经配置的是否匹配
*/ 
class FormRuleUtils {
    private rule: {[key: string]: any} = []
    private cb: {[key:string]: any} = []
    setCheck(data: dataFormat){
        this.cb[data.name] = data.cb == null ? ()=>{return true}: data.cb;

        const callback = (rule: any, value: any, cb: any, source: any, options: any) => {
            this.cb[data.name]() ? cb() : data.message == null ? cb(new Error()) : cb(new Error(data.message));
          }

        this.rule[data.name] = {
            required: data.required == null ? true: data.required,
            validator: callback,
            trigger: ['blur', 'change'] 
        }
        return this;
    }

    setChecks(datas: dataFormat[]){
        for(let i in datas){
            this.setCheck(datas[i]);
        }
        return this;
    }

    getRules(){
        return this.rule;
    }
    check():boolean{
        for(let key in this.cb){
            if(!this.cb[key]()){
                return false;
            }
        }
        return true;
    }
}

export const ruleUtils = FormRuleUtils